import {NavType} from "plain-micro-application";
import {defer, designPage, useRefs} from "plain-design-composition";
import ReactDOM from "react-dom";
import qs from 'qs'

export function registryUmiPages(nav: NavType) {
    nav.micro.registry({
        name: 'iframe嵌入umi子应用',
        type: 'React',
        pattern: ['sub-router-umi'],
        singleCase: true,
        loader: async (data) => {

            const host = process.env.NODE_ENV === 'development' ? 'http://localhost:3132' : 'http://martsforever-demo.gitee.io'
            const publicPath = '/temp-umi-reactrouter/'
            const pattern = '/sub-router-umi/'
            const pure = new Date().getSeconds()

            const {el, onShowPage} = data
            const {refs, onRef} = useRefs({
                iframe: {} as HTMLIFrameElement
            })
            const onFrameLoad = defer()
            const IframePage = designPage(() => {
                return () => (
                    <div style={{height: '100%', width: '100%'}}>
                        <iframe
                            ref={onRef.iframe}
                            frameBorder={0}
                            src={`${host}${publicPath}empty?pure=${pure}`}
                            style={{height: '100%', width: '100%', border: 'none'}}
                            onLoad={() => onFrameLoad.resolve()}
                        />
                    </div>
                )
            })
            ReactDOM.render((<IframePage/>), el)
            if (!onShowPage) {
                throw new Error('onShowPage不能为空')
            }

            const microMessageId = Date.now()
            let prevPath = ''

            onShowPage(async (page) => {
                await onFrameLoad.promise
                let [path, search] = page.path.replace(/^\/?sub-router-umi\//, '/').split('?')
                const param = {...page.param, ...!!search ? qs.parse(search) : {}, pure: 1}
                // console.log(path, param)
                prevPath = path + '?' + qs.stringify(param)
                // console.log(prevPath)
                window.history.pushState({}, '', data.entryPublicPath + pattern.slice(1, -1) + prevPath)
                refs.iframe!.contentWindow!.postMessage({microMessageId, path: prevPath}, host)
            })

            window.addEventListener('message', e => {
                if (e.data.microMessageId !== microMessageId) {return}
                if (e.data.path == prevPath) {return;}
                prevPath = e.data.path
                window.history.pushState({}, '', data.entryPublicPath + pattern.slice(1, -1) + prevPath)
            })

            return () => ReactDOM.unmountComponentAtNode(el)
        },
    })
}